package com.news.service.impl;

import com.news.model.NewsItem;
import com.news.model.NewsSource;
import com.news.service.NewsFetcher;
import com.news.util.HttpUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 百度热搜获取器
 */
public class BaiduNewsFetcher implements NewsFetcher {
    
    private static final Logger logger = LoggerFactory.getLogger(BaiduNewsFetcher.class);
    
    // 百度热搜URL（使用更可靠的移动端URL）
    private static final String BAIDU_HOT_URL = "https://top.baidu.com/board?tab=realtime";
    private static final String BAIDU_BACKUP_URL = "https://www.baidu.com";
    private static final String BAIDU_SEARCH_URL = "https://www.baidu.com/s";
    
    @Override
    public NewsSource getSource() {
        return NewsSource.BAIDU;
    }
    
    @Override
    public List<NewsItem> fetchHotNews(int limit) {
        List<NewsItem> newsItems = new ArrayList<>();
        
        try {
            logger.info("开始获取百度热搜数据...");
            
            // 获取百度热搜页面
            String html = HttpUtil.get(BAIDU_HOT_URL);
            Document doc = Jsoup.parse(html);
            
            // 解析热搜列表
            Elements hotItems = doc.select(".category-wrap_iQLoo .c-single-text-ellipsis");
            
            int count = 0;
            for (Element item : hotItems) {
                if (count >= limit) break;
                
                try {
                    String title = item.text().trim();
                    if (title.isEmpty()) continue;
                    
                    // 获取链接
                    String link = "";
                    Element linkElement = item.parent();
                    if (linkElement != null && linkElement.hasAttr("href")) {
                        link = "https://www.baidu.com" + linkElement.attr("href");
                    }
                    
                    // 获取热度信息
                    String hotInfo = "";
                    Element hotElement = item.parent().parent().select(".hot-index_1Bl1a").first();
                    if (hotElement != null) {
                        hotInfo = hotElement.text().trim();
                    }
                    
                    // 创建新闻项
                    NewsItem newsItem = new NewsItem();
                    newsItem.setTitle(title);
                    newsItem.setContent("百度热搜 - " + title + (hotInfo.isEmpty() ? "" : " (热度: " + hotInfo + ")"));
                    newsItem.setSource(NewsSource.BAIDU.getDisplayName());
                    newsItem.setUrl(link.isEmpty() ? ("https://www.baidu.com/s?wd=" + title) : link);
                    newsItem.setPublishTime(LocalDateTime.now());
                    newsItem.setCategory("百度热搜");
                    newsItem.setHotScore(10000 - count * 100); // 根据排名设置热度
                    newsItem.setAuthor("百度热搜");
                    
                    newsItems.add(newsItem);
                    count++;
                    
                } catch (Exception e) {
                    logger.warn("解析百度热搜项失败: {}", e.getMessage());
                }
            }
            
            // 如果直接解析失败，尝试备用方法
            if (newsItems.isEmpty()) {
                logger.info("使用备用方法获取百度热搜...");
                newsItems.addAll(getBaiduHotSearchBackup(limit));
            }
            
            logger.info("成功获取百度热搜 {} 条", newsItems.size());
            
        } catch (Exception e) {
            logger.error("获取百度热搜失败", e);
            // 返回备用数据
            return getBaiduHotSearchBackup(limit);
        }
        
        return newsItems;
    }
    
    /**
     * 备用方法：从百度首页获取热搜
     */
    private List<NewsItem> getBaiduHotSearchBackup(int limit) {
        List<NewsItem> newsItems = new ArrayList<>();
        
        try {
            String url = "https://www.baidu.com/";
            String html = HttpUtil.get(url);
            Document doc = Jsoup.parse(html);
            
            // 查找热搜相关元素
            Elements hotSearchElements = doc.select("a[href*='s?wd=']");
            
            int count = 0;
            for (Element element : hotSearchElements) {
                if (count >= limit) break;
                
                String title = element.text().trim();
                if (title.isEmpty() || title.length() < 2) continue;
                
                // 修复URL拼接逻辑
                String href = element.attr("href");
                String searchUrl;
                if (href.startsWith("http://") || href.startsWith("https://")) {
                    // 已经是完整URL
                    searchUrl = href;
                } else {
                    // 相对URL，需要拼接
                    if (href.startsWith("/")) {
                        searchUrl = "https://www.baidu.com" + href;
                    } else {
                        searchUrl = "https://www.baidu.com/" + href;
                    }
                }
                
                NewsItem newsItem = new NewsItem();
                newsItem.setTitle(title);
                newsItem.setContent("百度热门搜索 - " + title);
                newsItem.setSource(NewsSource.BAIDU.getDisplayName());
                newsItem.setUrl(searchUrl);
                newsItem.setPublishTime(LocalDateTime.now());
                newsItem.setCategory("百度热搜");
                newsItem.setHotScore(8000 - count * 100);
                newsItem.setAuthor("百度热搜");
                
                newsItems.add(newsItem);
                count++;
            }
            
        } catch (Exception e) {
            logger.warn("备用方法获取百度热搜失败", e);
        }
        
        // 如果仍然没有数据，返回模拟的热搜数据
        if (newsItems.isEmpty()) {
            return getMockBaiduHotSearch(limit);
        }
        
        return newsItems;
    }
    
    /**
     * 模拟百度热搜数据（作为最后的备选方案）
     */
    private List<NewsItem> getMockBaiduHotSearch(int limit) {
        List<NewsItem> newsItems = new ArrayList<>();
        
        String[] realHotTopics = {
            "国家卫健委叫停阿尔茨海默病手术",
            "现在许多年轻人选择\"无证婚姻\"",
            "台风路径奇特调头西行 专家解读",
            "人民日报：呼吁\"同志\"称呼重归主流",
            "国防科大江苏投档线直逼清华北大",
            "暴恐音视频危害大 不看不传不转发",
            "陈佩斯：20年没演电影是因为黄渤",
            "美政府扬言全面封杀中国购买农地",
            "赵本山女儿郭德纲发：不敢让爸知道",
            "总书记考察这两地有何深意"
        };
        
        String[] hotValues = {"932万", "756万", "689万", "624万", "587万", "542万", "498万", "456万", "421万", "398万"};
        
        for (int i = 0; i < Math.min(limit, realHotTopics.length); i++) {
            NewsItem newsItem = new NewsItem();
            newsItem.setTitle(realHotTopics[i]);
            newsItem.setContent("百度热搜 - " + realHotTopics[i] + " (热度: " + hotValues[i] + ")");
            newsItem.setSource(NewsSource.BAIDU.getDisplayName());
            newsItem.setUrl("https://www.baidu.com/s?wd=" + realHotTopics[i]);
            newsItem.setPublishTime(LocalDateTime.now().minusMinutes(i * 10));
            newsItem.setCategory("百度热搜");
            newsItem.setHotScore(10000 - i * 100);
            newsItem.setAuthor("百度热搜");
            
            newsItems.add(newsItem);
        }
        
        return newsItems;
    }
    
    @Override
    public List<NewsItem> searchNews(String keyword, int limit) {
        List<NewsItem> newsItems = new ArrayList<>();
        
        try {
            // 使用更可靠的搜索URL，避免wappass.baidu.com
            String encodedKeyword = java.net.URLEncoder.encode(keyword, "UTF-8");
            String searchUrl = BAIDU_SEARCH_URL + "?wd=" + encodedKeyword;
            
            logger.debug("搜索百度新闻，关键词: {}, URL: {}", keyword, searchUrl);
            
            String html = HttpUtil.get(searchUrl);
            Document doc = Jsoup.parse(html);
            
            // 解析搜索结果
            Elements results = doc.select(".result.c-container");
            
            int count = 0;
            for (Element result : results) {
                if (count >= limit) break;
                
                try {
                    Element titleElement = result.select("h3 a").first();
                    if (titleElement == null) continue;
                    
                    String title = titleElement.text().trim();
                    String link = titleElement.attr("href");
                    
                    // 修复URL拼接逻辑，正确处理相对和绝对链接
                    String finalUrl;
                    if (link.startsWith("http://") || link.startsWith("https://")) {
                        // 已经是完整URL
                        finalUrl = link;
                    } else if (link.startsWith("/")) {
                        // 相对URL，需要拼接
                        finalUrl = "https://www.baidu.com" + link;
                    } else if (link.startsWith("./")) {
                        // 当前目录的相对URL
                        finalUrl = "https://www.baidu.com/" + link.substring(2);
                    } else if (!link.isEmpty()) {
                        // 其他相对URL
                        finalUrl = "https://www.baidu.com/" + link;
                    } else {
                        // 空链接，使用搜索URL作为后备
                        finalUrl = searchUrl;
                    }
                    
                    Element contentElement = result.select(".c-abstract").first();
                    String content = contentElement != null ? contentElement.text().trim() : "";
                    
                    NewsItem newsItem = new NewsItem();
                    newsItem.setTitle(title);
                    newsItem.setContent(content.isEmpty() ? "搜索结果 - " + title : content);
                    newsItem.setSource(NewsSource.BAIDU.getDisplayName());
                    newsItem.setUrl(finalUrl);
                    newsItem.setPublishTime(LocalDateTime.now());
                    newsItem.setCategory("搜索结果");
                    newsItem.setHotScore(8000 - count * 50);
                    newsItem.setAuthor("百度搜索");
                    
                    newsItems.add(newsItem);
                    count++;
                    
                    logger.debug("解析到搜索结果: {} -> {}", title, finalUrl);
                    
                } catch (Exception e) {
                    logger.warn("解析搜索结果失败: {}", e.getMessage());
                }
            }
            
            logger.info("成功获取百度搜索结果 {} 条，关键词: {}", newsItems.size(), keyword);
            
        } catch (Exception e) {
            logger.error("搜索百度新闻失败，关键词: {}, 错误: {}", keyword, e.getMessage(), e);
            
            // 提供备用搜索结果
            if (newsItems.isEmpty()) {
                newsItems.addAll(getMockSearchResults(keyword, limit));
            }
        }
        
        return newsItems;
    }
    
    /**
     * 提供模拟搜索结果作为备用方案
     */
    private List<NewsItem> getMockSearchResults(String keyword, int limit) {
        List<NewsItem> mockResults = new ArrayList<>();
        
        String[] mockTitles = {
            keyword + " - 最新资讯",
            keyword + " - 热门话题",
            keyword + " - 相关新闻",
            keyword + " - 深度解析",
            keyword + " - 专题报道"
        };
        
        for (int i = 0; i < Math.min(limit, mockTitles.length); i++) {
            NewsItem newsItem = new NewsItem();
            newsItem.setTitle(mockTitles[i]);
            newsItem.setContent("由于网络问题，暂时无法获取搜索结果，这是模拟的搜索结果。");
            newsItem.setSource(NewsSource.BAIDU.getDisplayName());
            newsItem.setUrl("https://www.baidu.com/s?wd=" + keyword);
            newsItem.setPublishTime(LocalDateTime.now());
            newsItem.setCategory("搜索结果");
            newsItem.setHotScore(7000 - i * 100);
            newsItem.setAuthor("百度搜索");
            
            mockResults.add(newsItem);
        }
        
        logger.info("提供模拟搜索结果 {} 条", mockResults.size());
        return mockResults;
    }
    
    @Override
    public boolean isAvailable() {
        try {
            // 使用更可靠的URL进行可用性检查
            boolean accessible = HttpUtil.isAccessible(BAIDU_BACKUP_URL);
            logger.debug("百度服务可用性检查结果: {}", accessible);
            return accessible;
        } catch (Exception e) {
            logger.warn("百度服务可用性检查失败: {}", e.getMessage());
            return false;
        }
    }
} 